package com.zonski.jbots.engine.collision;

import java.util.Hashtable;
import java.util.Vector;

import com.zonski.jbots.engine.*;

/**
 * Implementation of CollisionEffect that delegates to different
 * collision effects depending on the type of entity that
 * a collision is with
 */
public final class CompositeCollisionEffect implements CollisionEffect
{
    private QuickVector effects;
    private CollisionEffect defaultEffect;

    public CompositeCollisionEffect(CollisionEffect defaultEffect)
    {
        this.defaultEffect = defaultEffect;
    }

    public final void addEffect(int entityTypeId, CollisionEffect effect)
    {
        EntityType entityType = EntityType.getEntityType(entityTypeId);
        int id = entityType.getId();
        if(this.effects == null)
        {
            this.effects = new QuickVector(id+1);
        }
        while(this.effects.size() <= id)
        {
            this.effects.addElement(new Object());
        }
        this.effects.setElementAt(effect, id);
    }

    public final boolean apply(Entity entity, Engine engine, CollisionData collision)
    {
        CollisionEffect effect;
        effect = getCollisionEffect(collision.with.entityType);
        return effect.apply(entity, engine, collision);
    }

    public final int getCollisionType(Entity entity, Entity with)
    {
        CollisionEffect effect;
        effect = getCollisionEffect(with.entityType);
        return effect.getCollisionType(entity, with);
    }

    private final CollisionEffect getCollisionEffect(EntityType type)
    {
        int id = type.getId();
        Object e;
        if(id < effects.size())
        {
            e = this.effects.elementAt(id);
        }else{
            e = null;
        }
        if(e instanceof CollisionEffect)
        {
            return (CollisionEffect)e;
        }else{
            return this.defaultEffect;
        }
    }
}
